package yxy.apple.util.concurrent;

import java.util.concurrent.TimeUnit;

/** */
public class ExecuteWrapper implements Runnable {

	private final Runnable runnable;

	public  ExecuteWrapper(Runnable runnable) {
		this.runnable = runnable;
	}

	@Override
	public final void run() {
		ExecuteWrapper.execute(runnable, getMaximumRuntimeInMillisecWithoutWarning());
	}

	protected long getMaximumRuntimeInMillisecWithoutWarning() {
		return Long.MAX_VALUE;
	}

	public static void execute(Runnable runnable) {
		execute(runnable, Long.MAX_VALUE);
	}

	public static void execute(Runnable runnable, long maximumRuntimeInMillisecWithoutWarning) {
		long begin = System.nanoTime();

		try {
			runnable.run();
		} catch (RuntimeException e) {
//			ThreadPoolManager.getInstance().publish(new ThreadPoolManagerLogger("线程处理出现错误：s%", e.getMessage()));
			System.err.println("线程处理出现错误:" + e.getMessage());
		}
		try {
			long runtimeInNanosec = System.nanoTime() - begin;
			Class<? extends Runnable> clazz = runnable.getClass();

			RunnableStatsManager.handleStats(clazz, runtimeInNanosec);

			long runtimeInMillisec = TimeUnit.NANOSECONDS.toMillis(runtimeInNanosec);

			if (runtimeInMillisec > maximumRuntimeInMillisecWithoutWarning) {
//				ThreadPoolManager.getInstance().publish(new ThreadPoolManagerLogger("s% - 执行时间过长：d% ms", clazz.getName(), runtimeInMillisec));
				System.err.println("线程执行时间过长::	thread:" + clazz.getName()+"	:time:"+runtimeInMillisec);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
